//
//  GLAFRequest.m
//  太平人寿 - 1
//
//  Created by rimi on 14-6-9.
//  Copyright (c) 2014年 rimi. All rights reserved.
//

#import "GLAFRequest.h"
#import "AFHTTPRequestOperationManager.h"
#import "ActivityIndicatorBgView.h"
#import "AppDelegate.h"
#import "UIImageView+WebCache.h"
#import "SGInfoAlert.h"

@interface GLAFRequest ()<UIAlertViewDelegate>
{
    
}
@end

static const NSInteger _TO_LOGIN = 1004;
static const NSInteger _SHOW_MESSAGE = 1003;
//static const NSInteger _TO_VALIDATE = 1005;
static const NSInteger _UNKNOW_ERROR = 1007;
//static const NSInteger _VALIDATE_ERROR = 1010;
static const NSInteger _VERSION_DISCARD = 1013;//可取消升级
static const NSInteger _TO_UPDATE = 1009;//强制更新

@implementation GLAFRequest


+ (NSDictionary *)paramsDic:(NSDictionary *)paramsDic urlstring:(NSString *)urlString
{
    NSMutableDictionary *paramsDics = [[NSMutableDictionary alloc] initWithDictionary:paramsDic];
    
    [paramsDics setObject:@2 forKey:@"mob"];
    [paramsDics setObject:@2 forKey:@"plantform"];
    [paramsDics setObject:@"shop" forKey:@"apptype"];
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    NSString* versionNum =[infoDict objectForKey:@"CFBundleShortVersionString"];
    [paramsDics setObject:versionNum forKey:@"appversion"];
    NSString *appid = [[NSUserDefaults standardUserDefaults] objectForKey:@"appid"];
    NSString *lastTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"applasttime"];
    //检查是否存在appid
    if (appid != nil && lastTime !=nil) {
        [paramsDics setObject:appid forKey:@"appid"];
        [paramsDics setObject:lastTime forKey:@"applasttime"];
    }else
    {
        [paramsDics setObject:@"0" forKey:@"applasttime"];
        [paramsDics setObject:@1 forKey:@"newapp"];
    }
    User_member *cur_member = [User_member instance];
    NSString *memberupdate = [NSString stringWithFormat:@"%ld",cur_member.memberupdate];
    if (memberupdate != nil) {
        [paramsDics setObject:memberupdate forKey:@"memberupdate"];
    }
    //请求以c开头
    if (![urlString hasPrefix:@"http"]) {
        //请求链接
        urlString = [NSString stringWithFormat:@"%@%@",baseurl_url,urlString];
        //获取post参数
        NSString *passport = cur_member.passport;
        NSString *supe_uid = [NSString stringWithFormat:@"%ld",(long)cur_member.uid];
        if (passport != nil) {
            [paramsDics setObject:passport forKey:@"passport"];
        }else{
            [paramsDics setObject:@"0" forKey:@"passport"];
        }
        [paramsDics setObject:supe_uid forKey:@"supe_uid"];
    }
    NSDictionary *dic = @{@"paramsDics":paramsDics,
                          @"urlString":urlString};
    return dic;
}

+ (void)updateGlobalDataBefore:(id)responseObject
{
    User_member *cur_member=[User_member instance];
    if (responseObject != nil) {
        if (responseObject[@"a_appconfig"] != nil) {
            NSString *appid = responseObject[@"a_appconfig"][@"appid"];
            NSString *lastTime = responseObject[@"a_appconfig"][@"applasttime"];
            if (appid != nil) {
                [[NSUserDefaults standardUserDefaults] setObject:appid forKey:@"appid"];
            }
            if (lastTime != nil) {
                [[NSUserDefaults standardUserDefaults] setObject:lastTime forKey:@"applasttime"];
            }
        }
#pragma mark--时时更新a_memberupdateobj
        //时时更新a_memberupdateobj
        
        NSArray *allkeys = cur_member.getPropertyList;
        if ([allkeys count] != 0 && responseObject[@"a_memberupdateobj"] != nil) {
            for (int i=0; i<[allkeys count]; i++) {
                if ([allkeys[i] isEqualToString:@"uid"] && responseObject[@"a_memberupdateobj"][@"supe_uid"] != nil) {
                    [cur_member setValue:responseObject[@"a_memberupdateobj"][@"supe_uid"] forKey:@"uid"];
                }
                if (responseObject[@"a_memberupdateobj"][allkeys[i]] != nil) {
                    [cur_member setValue:responseObject[@"a_memberupdateobj"][allkeys[i]] forKey:allkeys[i]];
                }
            }
            [cur_member updateAll];
        }
    }
}

+ (void)checkPublicData:(id)responseObject paramsDic:(NSDictionary *)paramsDic defaultAction:(BOOL)defaultAction
{
    if (responseObject != nil) {
        NSString *string;
        if ([responseObject[@"code"] integerValue] == _VERSION_DISCARD) {
            [Common doInMainThread:^{
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"" message:@"版本过低，是否下载新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                alter.tag = 999999;
                [alter show];
            }];
            return;
        }
        if ([responseObject[@"code"] integerValue] == _TO_UPDATE) {
            [Common doInMainThread:^{
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"" message:@"版本过低，请更新后登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                alter.tag = 999998;
                [alter show];
            }];
            return;
        }
        if ([responseObject[@"code"] integerValue] == _TO_LOGIN) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_TOLOGIN object:@"账号在别处登录，请重新登录"];
            [Common tip:@"账号在其他地方登录，请重新登录"];
        }else
            if ([responseObject[@"code"] integerValue] == _SHOW_MESSAGE) {
                if(defaultAction){
                    string = responseObject[@"msg"];
                    [Common tip:string];
                }
            }else
                if ([responseObject[@"code"] integerValue] == _UNKNOW_ERROR) {
                    if(defaultAction){
                        string = @"未知错误";
                        [Common tip:string];
                    }
                }else
                    if ([responseObject[@"code"] integerValue] == _TO_UPDATE) {
                        if(defaultAction){
                            string = @"请更新应用";
                            [Common tip:string];
                        }
                    }
    }
}

+ (void)startRequest:(NSString *)urlString
           paramsDic:(NSDictionary *)paramsDic
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess{
    
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic defaultdialog:YES
           defaultNetworkfail:YES
                      isTouch:NO
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:nil
                  netWorkFail:nil
               handleLongTime:nil];
}

+ (void)startRequest:(NSString *)urlString
      defaultdialog :(BOOL)defaultdialog
           paramsDic:(NSDictionary *)paramsDic
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
         netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail
{
    
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic
                defaultdialog:defaultdialog
           defaultNetworkfail:YES
                      isTouch:NO
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:nil
                  netWorkFail:netWorkFail handleLongTime:nil];
}

+ (void)startRequest:(NSString *)urlString
      defaultdialog :(BOOL)defaultdialog
  defaultNetworkfail:(BOOL)defaultNetworkfail
           paramsDic:(NSDictionary *)paramsDic
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
         netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail
{
    
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic
                defaultdialog:defaultdialog
           defaultNetworkfail:defaultNetworkfail
                      isTouch:NO
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:nil
                  netWorkFail:netWorkFail handleLongTime:nil];
}

+ (void)startRequest:(NSString *)urlString
             istouch:(BOOL)istouch
           paramsDic:(NSDictionary *)paramsDic
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
{
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic defaultdialog:YES
           defaultNetworkfail:YES
                      isTouch:istouch
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:doFinally
                  netWorkFail:nil handleLongTime:nil];
}

+ (void)startRequest:(NSString *)urlString
           paramsDic:(NSDictionary *)paramsDic
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
{
    
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic defaultdialog:YES
           defaultNetworkfail:YES
                      isTouch:NO
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:doFinally
                  netWorkFail:nil handleLongTime:nil];
}

+ (void)startRequest:(NSString *)urlString
           paramsDic:(NSDictionary *)paramsDic
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
         netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail
{
    
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic defaultdialog:YES
           defaultNetworkfail:YES
                      isTouch:NO
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:nil
                  netWorkFail:netWorkFail handleLongTime:nil];
}

+ (void)startRequest:(NSString *)urlString
           paramsDic:(NSDictionary *)paramsDic
      defaultdialog :(BOOL)defaultdialog
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
{
    
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic defaultdialog:defaultdialog
           defaultNetworkfail:YES
                      isTouch:NO
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:doFinally
                  netWorkFail:nil handleLongTime:nil];
}

+ (void)startRequest:(NSString *)urlString
           paramsDic:(NSDictionary *)paramsDic
      defaultdialog :(BOOL)defaultdialog
              ispost:(BOOL)post
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
{
    
    [GLAFRequest startRequest:urlString time:(NSInteger)nil ispost:post paramsDic:paramsDic picDic:nil isTouch:NO defaultdialog:defaultdialog defaultNetworkfail:NO defaultAction:YES handleSuccess:handleSuccess doFinally:doFinally netWorkFail:nil handleLongTime:nil progress:nil];
}

+ (void)startRequest:(NSString *)urlString
           paramsDic:(NSDictionary *)paramsDic
      defaultdialog :(BOOL)defaultdialog
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
         netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
{
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic defaultdialog:defaultdialog
           defaultNetworkfail:NO
                      isTouch:NO
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:doFinally
                  netWorkFail:netWorkFail handleLongTime:nil];
}

+ (void)startRequest:(NSString *)urlString
           paramsDic:(NSDictionary *)paramsDic
      defaultdialog :(BOOL)defaultdialog
 defaultNetworkfail :(BOOL)defaultNetworkfail
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
{
    
    [GLAFRequest startRequest:urlString
                    paramsDic:paramsDic defaultdialog:defaultdialog
           defaultNetworkfail:defaultNetworkfail
                      isTouch:NO
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:doFinally
                  netWorkFail:nil handleLongTime:nil];
}


+ (void)startRequest:(NSString *)urlString paramsDic:(NSDictionary *)paramsDic
      defaultdialog :(BOOL)defaultdialog
 defaultNetworkfail :(BOOL)defaultNetworkfail
             isTouch:(BOOL)isTouch
       defaultAction:(BOOL)defaultAction
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
         netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail
      handleLongTime:(void(^)(id sta,NSDictionary * paramsDic)) handleLongTime

{
    [GLAFRequest startRequest:urlString
                         time:(NSInteger)nil
     
                    paramsDic:paramsDic picDic:nil isTouch:isTouch defaultdialog:defaultdialog defaultNetworkfail:defaultNetworkfail defaultAction:defaultAction handleSuccess:handleSuccess doFinally:doFinally netWorkFail:netWorkFail handleLongTime:handleLongTime progress:nil];
    
}

+ (void)startFileRequest:(NSString *)urlString
                    time:(NSInteger)time
                 isTouch:(BOOL)isTouch
               paramsDic:(NSDictionary *)paramsDic
           defaultdialog:(BOOL)defaultdialog
                  picDic:(NSDictionary *)picDic
           handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
             netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail
{
    
    [GLAFRequest startRequest:urlString
                         time:(NSInteger)time
                    paramsDic:paramsDic
                       picDic:picDic
                      isTouch:isTouch
                defaultdialog:defaultdialog
           defaultNetworkfail:YES
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:nil
                  netWorkFail:netWorkFail handleLongTime:nil progress:nil];
}

+ (void)startFileRequest:(NSString *)urlString
                    time:(NSInteger)time
               paramsDic:(NSDictionary *)paramsDic
                  picDic:(NSDictionary *)picDic
           handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
                progress:(void(^)(id progressNum)) progress
             netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail

{
    
    [GLAFRequest startRequest:urlString
                         time:(NSInteger)time
                    paramsDic:paramsDic
                       picDic:picDic
                      isTouch:NO
                defaultdialog:NO
           defaultNetworkfail:YES
                defaultAction:YES
                handleSuccess:handleSuccess doFinally:nil
                  netWorkFail:netWorkFail handleLongTime:nil progress:progress];
}

+ (void)startRequest:(NSString *)urlString
                time:(NSInteger)time
           paramsDic:(NSDictionary *)paramsDic
              picDic:(NSDictionary *)picDic
             isTouch:(BOOL)isTouch
      defaultdialog :(BOOL)defaultdialog
 defaultNetworkfail :(BOOL)defaultNetworkfail
       defaultAction:(BOOL)defaultAction
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
         netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail
      handleLongTime:(void(^)(id sta,NSDictionary * paramsDic)) handleLongTime
            progress:(void(^)(id progressNum)) progress

{
    [GLAFRequest startRequest:urlString time:time ispost:YES paramsDic:paramsDic picDic:picDic isTouch:isTouch defaultdialog:defaultdialog defaultNetworkfail:defaultNetworkfail defaultAction:defaultAction handleSuccess:handleSuccess doFinally:doFinally netWorkFail:netWorkFail handleLongTime:handleLongTime progress:progress];
}


+ (void)startRequest:(NSString *)urlString
                time:(NSInteger)time
              ispost:(BOOL)post
           paramsDic:(NSDictionary *)paramsDic
              picDic:(NSDictionary *)picDic
             isTouch:(BOOL)isTouch
      defaultdialog :(BOOL)defaultdialog
 defaultNetworkfail :(BOOL)defaultNetworkfail
       defaultAction:(BOOL)defaultAction
       handleSuccess:(void(^)(id sta,NSDictionary * paramsDic)) handleSuccess
           doFinally:(void(^)(NSDictionary * paramsDic)) doFinally
         netWorkFail:(void(^)(NSDictionary * paramsDic))netWorkFail
      handleLongTime:(void(^)(id sta,NSDictionary * paramsDic)) handleLongTime
            progress:(void(^)(id progressNum)) progress

{
    //创建自定义的活动指示器视图
    ActivityIndicatorBgView *indicatorView;
    if(defaultAction&&defaultdialog){
        AppDelegate * appdelegate= (AppDelegate *)[UIApplication sharedApplication].delegate;
        indicatorView = [[ActivityIndicatorBgView alloc] init];
        indicatorView.frame = CGRectMake(0, 0, CGRectGetWidth(appdelegate.window.bounds), CGRectGetHeight(appdelegate.window.bounds));
        indicatorView.center = CGPointMake(CGRectGetMidX(appdelegate.window.bounds), CGRectGetMidY(appdelegate.window.bounds));
        indicatorView.layer.cornerRadius = 6.0;
        indicatorView.isTouch = isTouch;
        [indicatorView startAnimating];
        [appdelegate.window addSubview:indicatorView];
    }
    
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[GLAFRequest paramsDic:paramsDic urlstring:urlString]];
    paramsDic = dic[@"paramsDics"];
    urlString = dic[@"urlString"];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    if (time != 0) {
        manager.requestSerializer.timeoutInterval = time;
    }else
    {
        manager.requestSerializer.timeoutInterval = 30;
    }
    void (^ success)(AFHTTPRequestOperation *operation, id responseObject);
    success=^(AFHTTPRequestOperation *operation, id responseObject) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            @try {
                [GLAFRequest checkPublicData:responseObject paramsDic:paramsDic defaultAction:defaultAction];
                [GLAFRequest updateGlobalDataBefore:responseObject];
                if(handleLongTime){
                    handleLongTime(responseObject,paramsDic);
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    @try {
                        if(defaultdialog){
                            [indicatorView stopAnimating];
                        }
                        if(responseObject){
                            handleSuccess(responseObject,paramsDic);
                        }
                    }
                    @catch (NSException *exception) {}
                    @finally{
                        if(doFinally){
                            if (picDic) {
                                doFinally(picDic);
                            }else
                            {
                                doFinally(paramsDic);
                            }
                        }
                    }
                });
            }
            @catch (NSException *exception) {
                if(defaultdialog){
                    [indicatorView stopAnimating];
                }
                
                if(doFinally){
                    if (picDic) {
                        doFinally(picDic);
                    }else
                    {
                        doFinally(paramsDic);
                    }
                }
            }
        });
        
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error);
    failure=^(AFHTTPRequestOperation *operation, NSError *error) {
        @try {
            if (defaultNetworkfail==YES) {
                [Common tip:@"请求失败，请稍后再试"];
            }
            if(defaultdialog){
                [indicatorView stopAnimating];
            }
            if(netWorkFail){
                if (picDic) {
                    netWorkFail(picDic);
                }else
                {
                    netWorkFail(paramsDic);
                }
            }
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            if(doFinally){
                if (picDic) {
                    doFinally(picDic);
                }else
                {
                    doFinally(paramsDic);
                }
            }
        }
    };
    
    if(picDic){
        NSString *url = [NSString stringWithFormat:@"%@&appid=%@&applasttime=%@&appversion=%@&memberupdate=%@&mob=%@&passport=%@&supe_uid=%@",urlString,paramsDic[@"appid"],paramsDic[@"applasttime"],paramsDic[@"appversion"],paramsDic[@"memberupdate"],paramsDic[@"mob"],paramsDic[@"passport"],paramsDic[@"supe_uid"]];
        void (^constructingBodyWithBlock)(id <AFMultipartFormData> formData);
        constructingBodyWithBlock=^(id<AFMultipartFormData> formData){
            for (NSString *key in picDic) {
                UIImage *image=(UIImage *)picDic[key];
                
                NSData * data =  UIImageJPEGRepresentation(image, 0.5);
                [formData appendPartWithFileData:data name:key fileName:@"121.jpeg" mimeType:@"jpg/jpeg"];
            }
        };
        AFHTTPRequestOperation *operation = [manager POST:url parameters:paramsDic
                                constructingBodyWithBlock:constructingBodyWithBlock
                                                  success:success
                                                  failure:failure];
        if(progress){
            [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                                long long totalBytesWritten,
                                                long long totalBytesExpectedToWrite) {
                NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
                CGFloat a = totalBytesWritten;
                CGFloat b = totalBytesExpectedToWrite;
                NSNumber *x =  [NSNumber numberWithFloat:a/b];
                progress(x);
            }];
            [operation start];
        }
    }else{
        if (post==YES) {
            [manager POST:urlString parameters:paramsDic success:success failure:failure];
        }else{
//            NSString *url = [NSString stringWithFormat:@"%@&appid=%@&applasttime=%@&appversion=%@&memberupdate=%@&mob=%@&passport=%@&supe_uid=%@",urlString,paramsDic[@"appid"],paramsDic[@"applasttime"],paramsDic[@"appversion"],paramsDic[@"memberupdate"],paramsDic[@"mob"],paramsDic[@"passport"],paramsDic[@"supe_uid"]];
            [manager GET:urlString parameters:paramsDic success:success failure:failure];
        }
    }
}

+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //是否升级，可取消
    if (alertView.tag == 999999) {
        if (buttonIndex == 0) {
            
        }
    }else if (alertView.tag == 999998)//强制必须升级
    {
        if (buttonIndex == 0) {
            
        }
    }else if (alertView.tag == 999997)//重新登录
    {
        [Common addAlert:@"账号在其他地方登录，请重新登录"];
    }
}


@end
